package org.huangrui.juc.day04.locks;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author hr
 * @Create 2024-03-31 05:13
 */
public class T02_ThreadIncrDecr {
    public static void main(String[] args) {
        Share share = new Share();
        new Thread(() ->{
           for (int i = 1; i <= 10; i++) {
                  share.incr();
           }
        },"AA").start();

        new Thread(() ->{
            for (int i = 1; i <= 10; i++) {
                share.decr();
            }
        },"BB").start();

        new Thread(() ->{
            for (int i = 1; i <= 10; i++) {
                share.incr();
            }
        },"CC").start();

        new Thread(() ->{
            for (int i = 1; i <= 10; i++) {
                share.decr();
            }
        },"DD").start();
    }
}
//第一步 创建资源类，定义属性和操作方法
class Share {
    //初始值
    private int number = 0;
    //创建Lock
    private final Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();
    //+1的方法
    public void incr(){
        lock.lock();
        try {//判断
            while (number != 0) {
                condition.await();
            }//干活
            number++;
            System.out.println(Thread.currentThread().getName()+" :: "+number);
            //通知
            condition.signalAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    //-1的方法
    public void decr(){
        lock.lock();
        try {
            while (number == 0) {
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName()+" :: "+number);
            condition.signalAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}
